package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.mapper.ApAuthorMapper;
import com.heima.article.service.GeneratePageService;
import com.heima.commom.exception.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApAuthor;
import com.heima.model.common.enums.AppHttpCodeEnum;
import freemarker.template.Configuration;
import freemarker.template.Template;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @author by jojo
 * @Date 2022/3/7
 * @Description
 */
@Service
@Slf4j
public class GeneratePageServiceImpl implements GeneratePageService {
    @Autowired
    @Qualifier("minIOFileStorageService")
    private FileStorageService fileStorageService;
    @Value("${file.minio.prefix}")
    private String prefix;
    @Autowired
    private ApArticleMapper apArticleMapper;
    @Autowired
    private ApAuthorMapper authorMapper;
    @Autowired
    private Configuration configuration;


    @Override
    public void generateArticlePage(String content, ApArticle apArticle) {
        try {
            //1.获取模板对象
            Template template = configuration.getTemplate("article.ftl");
            //2.准备替换模板的数据
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSON.parseArray(content));
            map.put("article",apArticle);
            //查ApAuthorMapper
            ApAuthor apAuthor = authorMapper.selectById(apArticle.getAuthorId());
            map.put("authorApUserId",apAuthor.getUserId());
            //3.替换模板后得到的内容
            StringWriter writer = new StringWriter();
            template.process(map,writer);
            //4.将替换后的模板上传到minion
            InputStream inputStream = new ByteArrayInputStream(writer.toString().getBytes());
            String store = fileStorageService.store(prefix, apArticle.getId() + ".html", "text/html", inputStream);
            //5.将minion的html的地址保存到ApArticle表的static_url字段上
            apArticle.setStaticUrl(store);
            apArticleMapper.updateById(apArticle);
            log.info("静态页生成功 地址==》{}",store);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("生成静态页失败 --> 原因：{}",e.getMessage());
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,"生成静态页失败");
        }
    }
}
